<?php
/**
 * @version 	$Id:$
 * @author 		Luu Trong Hieu <tronghieu1012@yahoo.com>
 * @license 	GNU/GPL see license.php
 * @copyright 	Copyright (c) 2010 Luu Trong Hieu. All right reserved. 
 */
defined('IN_FLYWHEEL') or die('Restricted Access');
/**
 * User Controller
 * 
 * @package 	backend
 * @subpackage 	controller.login
 *
 */
class LoginController extends fController {
	public function executeDefault() {
		$this->executeLogin();
	}
	
	/**
	 * Logout Action
	 *
	 */
	public function executeLogout() {
		fFactory::getUser()->logout();
		fMessage::addMsg('login', fMessage::TYPE_SUCCESS, array('Logout Success' => ''));			
		$this->executeLogin();			
	}
	
	/**
	 * Login Action
	 *
	 */
	public function executeLogin() {
		$user = fFactory::getUser();
		if ($user->isAuthenticated()) {
			fRequest::redirect(fFactory::getRouter()->getBaseUrl());
		}
		
		$message = new fMessage('login');
		
		$request = fFactory::getRequest();
		if ($request->getMethod() == fRequest::POST) {			
			if(!$request->checkToken()) { // Check token
				fApplication::end('Invalid token!');
			}
			
			if ($user->login($request->post('username'), $request->post('password'))) {
				fRequest::redirect(fFactory::getRouter()->getBaseUrl());												
			}
			else {
				$message->add('The password or username you entered is incorrect. Please try again (make sure your caps lock is off).', 'Please re-enter your username and password!', fMessage::TYPE_ERROR);								
			}			
		}
		$msgHTML = fMessage::render($message);
		
		$this->setLayout('login');		
		$this->setView('login');
		$template = fFactory::getTemplate();
		$template->assign('token', fForm::renderCsrfProtection());
		$template->assign('action', fUri::createUrl('login'));
		if ($msgHTML) {
			$template->assign('message', $msgHTML);
		}
		$this->loadLanguage('user');		
	}
}